
import Taro from '@tarojs/taro';
import { MaterialIcons } from 'taro-icons';
import React, { useState, useEffect, useRef } from 'react';
import { View, Text, ScrollView, Textarea, Button, Image } from '@tarojs/components';
import ImageLoader from '../../components/ImageLoader';

import { formatDateTime } from '../../utils/common';
import { uploadUserFile } from '../../contexts/store';
import { useAppContext } from '../../contexts/AppContext';
import { ChatSessionMessageItem } from '../../types/chat';
import { DataLoadingView } from '../../components/dataLoading';
import {
  getChatSessionMessageApi, setChatSessionStatusApi,
  addChatSessionMessageApi, getLastestMessageApi
} from '../../api/chat';

import './index.scss';

/**
 * 聊天页面组件
 * 展示与教练的聊天会话内容
 */
const ChatRoom: React.FC = () => {
  const { userInfo } = useAppContext();
  const userId = Number(userInfo?.id);
  const userAvatar = userInfo?.avatar || '';
  const routerParams = Taro.getCurrentInstance().router?.params || {};
  const sessionId = routerParams.sessionId as string;
  const coachId = Number(routerParams.coachId);
  const coachName = decodeURIComponent(routerParams.coachName as string || '');
  const avatar = routerParams.coachAvatar as string || ''
  let coachAvatar = decodeURIComponent(avatar);
  // 状态管理
  const firstLoadRef = useRef(false);
  const lastMessageIdRef = useRef(0);
  const preMessageIdRef = useRef(0);
  const [inputText, setInputText] = useState('');
  const [hasMore, setHasMore] = useState(false);
  const [loading, setLoading] = useState(false);
  const [fetching, setFetching] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [scrollTop, setScrollTop] = useState(0);
  const [shouldScroll, setShouldScroll] = useState(true);
  const [loadingHistory, setLoadingHistory] = useState(false);
  const [showEmojiPanel, setShowEmojiPanel] = useState(false);
  const [messages, setMessages] = useState<ChatSessionMessageItem[]>([]);


  // 加载历史消息
  const loadHistoryMessages = async () => {
    if (!sessionId || !coachId) return;
    
    setLoadingHistory(true);
    setShouldScroll(false);
    try {
      const resp = await getChatSessionMessageApi(Number(sessionId), coachId, preMessageIdRef.current);
      if (resp.code === 200 && resp.data) {
        if (resp.data.result && resp.data.result.length > 0) {
          setHasMore(resp.data.has_more);
          preMessageIdRef.current = resp.data.start;
          setMessages(prev => [...resp.data.result, ...prev]);
          
          // 计算滚动位置
          const newScrollTop = resp.data.result.length * 100; // 估算每条消息高度
          setScrollTop(prev => prev + newScrollTop);
        }
      }
    } catch (error) {
      console.error('加载历史消息失败:', error);
      Taro.showToast({
        title: '加载历史消息失败',
        icon: 'none'
      });
    } finally {
      setLoadingHistory(false);
    }
  };

  // 获取初始消息列表
  const getInitMessageList = async () => {
    if (!sessionId) return;
    if (fetching) return;
    
    setFetching(true);
    setIsLoading(true);
    try {
      const resp = await getChatSessionMessageApi(Number(sessionId), coachId, 0);
      if (resp.code === 200 && resp.data) {
        lastMessageIdRef.current = resp.data.end;
        preMessageIdRef.current = resp.data.start;
        setHasMore(resp.data.has_more);
        setMessages(prev => [...prev, ...(resp.data.result || [])]);
        
        // 滚动到底部
        setTimeout(() => {
          setScrollTop(99999);
        }, 100);
      }
    } catch (error) {
      console.error('加载历史消息失败:', error);
      Taro.showToast({
        title: '加载历史消息失败',
        icon: 'none'
      });
    } finally {
      setIsLoading(false);
    }
  };

  // 获取最新消息
  const getLastestMessageList = async () => {
    if (!sessionId || !coachId) return;
    
    try {
      const resp = await getLastestMessageApi(Number(sessionId), lastMessageIdRef.current);
      if (resp.code === 200 && resp.data && resp.data.result && resp.data.result.length > 0) {
        lastMessageIdRef.current = resp.data.end;
        setMessages(prev => [...prev, ...resp.data.result]);
        
        // 滚动到底部
        if (shouldScroll) {
          setTimeout(() => {
            setScrollTop(99999);
          }, 100);
        }
      }
    } catch (error) {
      console.error('加载最新消息失败:', error);
    }
  };

  // 设置定时获取消息
  useEffect(() => {
    if (!sessionId) return;
    
    if (!firstLoadRef.current) {
      firstLoadRef.current = true;
      setChatSessionStatusApi(Number(sessionId));
      getInitMessageList();
    }
    
    // 设置2秒定时器获取消息
    const interval = setInterval(getLastestMessageList, 2000);
    return () => clearInterval(interval);
  }, [sessionId, coachId]);

  // 发送消息
  const handleSendMessage = async (messageType: 'text' | 'image' | 'emoji' = 'text', content?: string, tempFilePath?: string) => {
    if (!sessionId) {
      Taro.showToast({
        title: '会话初始化中，请稍候...',
        icon: 'none'
      });
      return;
    }

    const messageContent = content || inputText.trim();
    if (!messageContent && messageType !== 'image') {
      Taro.showToast({
        title: '请输入消息内容',
        icon: 'none'
      });
      return;
    }

    try {
      setLoading(true);
      const response = await addChatSessionMessageApi({
        id: 0,
        file_type: messageType === 'image' ? 1 : 0,
        coach_id: coachId,
        content: messageContent,
        session_id: Number(sessionId),
      });
      
      console.log('消息发送响应:', response);
      
      if (response.code === 200 && response.data) {
        lastMessageIdRef.current = response.data.id;
        
        // 创建完整的消息对象，确保符合ChatSessionMessageItem接口
        const newMessage: ChatSessionMessageItem = {
          id: response.data.id,
          content: response.data.content,
          file_url: response.data.file_url || (messageType === 'image' ? tempFilePath || '' : ''),
          file_type: response.data.file_type || (messageType === 'image' ? 1 : 0),
          user_id: userId,
          created_at: formatDateTime(new Date()),
          // 确保其他必要字段都有值
          session_id: Number(sessionId),
          coach_id: coachId,
        };
        
        // 使用setTimeout确保UI更新
        setTimeout(() => {
          setMessages(prev => [...prev, newMessage]);
          
          // 滚动到底部
          setTimeout(() => {
            setScrollTop(99999);
          }, 100);
        }, 0);
        
        // 清空输入框
        if (messageType === 'text') {
          setInputText('');
        }
        
        Taro.showToast({
          title: '消息发送成功',
          icon: 'success'
        });
      }
    } catch (error) {
      console.error('发送消息失败:', error);
      Taro.showToast({
        title: '消息发送失败，请重试',
        icon: 'none'
      });
    } finally {
      setLoading(false);
    }
  };

  // 处理图片上传
  const handleImageUpload = () => {
    Taro.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: async (res) => {
        const tempFilePath = res.tempFilePaths[0];
        try {
          setLoading(true);
          let fileType = tempFilePath.split(".").pop() || 'png';
          const res:any = await uploadUserFile(tempFilePath, 'chat.'+fileType, 'image/png', 'chat', userId);
          if (res.code === 200 && res.data) {
            await handleSendMessage('image', res.data.file_name, tempFilePath);
          }else {
            Taro.showToast({
              title: '图片上传失败，请重试',
              icon: 'none'
            });
          }
        } catch (error) {
          console.error('图片上传失败:', error);
          Taro.showToast({
            title: '图片上传失败，请重试',
            icon: 'none'
          });
        } finally {
          setLoading(false);
        }
      },
      fail: (err) => {
        console.error('图片选择失败:', err);
      }
    });
  };

  return (
    <View className="page-container chat-container">
      {/* 页面头部 */}
      <View className="chat-header">
        <View className="chat-avatar-username-group">
          <ImageLoader 
            className="chat-coach-avatar" 
            src={coachAvatar} 
            mode="aspectFill"
          />
          <Text className="chat-username">{coachName}</Text>
        </View>
      </View>

      {/* 消息列表 */}
      <ScrollView 
        className="chat-messages"
        scrollY
        refresherEnabled={true}
        scrollTop={scrollTop}
        onScroll={(e) => {
          const { scrollTop: currentScrollTop } = e.detail;
          setScrollTop(currentScrollTop);
          // 滚动到顶部时加载更多历史消息
          if (currentScrollTop === 0 && hasMore && !loadingHistory) {
            loadHistoryMessages();
          }
        }}
      >
        {isLoading ? (
          <DataLoadingView />
        ) : null}
        
        {hasMore && (
          <View className="chat-load-history-container">
            <Button 
              className="chat-load-history-button" 
              onClick={loadHistoryMessages}
              plain
              loading={loadingHistory}
            >
              加载历史消息
            </Button>
          </View>
        )}
        
        {messages.map((message) => (
          <View key={message.id} className="chat-message-group">
            <View className={`chat-message-item ${message.user_id === userId ? 'chat-user-message-wrapper' : 'chat-other-message-wrapper'}`}>
              {message.user_id !== userId && (
                <View className="chat-message-avatar">
                  <ImageLoader 
                    className="chat-avatar-small" 
                    src={coachAvatar} 
                    mode="aspectFill"
                  />
                </View>
              )}
              
              <View className="chat-message-content-wrapper">
                {message.user_id === userId ? (
                  <View className="chat-message-username">
                    <Text className="chat-username-text">我</Text>
                  </View>
                ):( 
                  <View className="chat-message-username">
                    <Text className="chat-username-text">{coachName}</Text>
                  </View>
                )}
                
                <View className={`chat-message-bubble ${message.user_id === userId ? 'chat-user-message' : 'chat-other-message'}`}>
                  {message.file_type === 1 && message.content ? (
                    <ImageLoader
                      className="chat-message-image" 
                      src={message.content} 
                      mode="aspectFit"
                      onClick={() => {
                        Taro.previewImage({
                          urls: [message.content]
                        });
                      }}
                    />
                  ) : (
                    <Text className="chat-message-text">{message.content}</Text>
                  )}
                </View>
                
                <View className="chat-message-time">
                  <Text className="chat-time-text">{message.created_at}</Text>
                </View>
              </View>
              
              {message.user_id === userId && (
                <View className="chat-message-avatar">
                  <ImageLoader 
                    className="chat-avatar-small" 
                    src={userAvatar} 
                    mode="aspectFill"
                  />
                </View>
              )}
            </View>
          </View>
        ))}
        
        {!loading && messages.length === 0 && (
          <View className="chat-empty-messages">
            <Text className="chat-empty-text">暂无消息~</Text>
          </View>
        )}
      </ScrollView>

      {/* 输入区域 */}
      <View className="chat-input-area">
        <View className="chat-input-controls">
          <View className="chat-input-control-btn" onClick={handleImageUpload}>
            <MaterialIcons name="image" color="#333" size={26} />
          </View>
        </View>
        
        <View className="chat-input-container">
          <Textarea
            value={inputText}
            onInput={(e) => setInputText(e.detail.value)}
            placeholder="输入消息..."
            maxlength={500}
            className="chat-message-input"
            disabled={loading}
            autoHeight
          />
          <View className={`chat-message-send-button ${!loading && inputText.trim().length > 0 ? '' : 'disabled'}`} onClick={() => handleSendMessage()}>
            <MaterialIcons name="send" color="#fff" size={20} />
          </View>
        </View>
      </View>
    </View>
  );
};

export default ChatRoom;